
package com.eascs.admin.o2o.detail.controller;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.credit.entity.CreditReport;
import com.eascs.admin.o2o.credit.service.CreditReportService;
import com.eascs.admin.o2o.detail.entity.OaLoanDetailEntity;
import com.eascs.admin.o2o.detail.entity.OaPay;
import com.eascs.admin.o2o.detail.form.DetailFrom;
import com.eascs.admin.o2o.detail.form.ShowDetailForm;
import com.eascs.admin.o2o.detail.service.LoanDetailService;
import com.eascs.admin.o2o.detail.service.OaLoanapplyDetailService;
import com.eascs.admin.o2o.enterpriseZX.entity.O2oEnterpriseZxEntity;
import com.eascs.admin.o2o.enterpriseZX.service.O2oEnterpriseZxService;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.OaLoanapply;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.service.AuditCommentService;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.OaLoanapplyService;
import com.eascs.admin.o2o.internal.service.PubDditemService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.O2oSDEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.service.O2oSdService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.specialInterview.entity.O2OSpecialInterview;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.afterloancheck.service.LoanCheckServicce;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.vo.BrandAndPartnerVo;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.nsEditDetail.entity.CustomerAssetInfo;
//import com.eascs.crm.common.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.file.FileTypeConstants;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.form.O2oPaymentsForm;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loan.service.O2oPaymentsService;
import com.eascs.overdue.entity.O2oOverdueReport;
import com.eascs.overdue.service.O2oOverdueService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.type.SystemModule;
import com.eascs.workflow.form.CreditForm;
import com.eascs.workflow.form.ZXPTCWForm;
import com.eascs.workflow.util.CreditTransforCreditFrom;

@Controller
public class LoanDetailMasterViewController extends BaseMasterViewController {
	private final Logger logger = LoggerFactory.getLogger(LoanDetailMasterViewController.class);
	@Autowired
	private O2oLoanapplyService o2oloanapplyService;
	@Autowired
	private O2oLoanService o2oLoanService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Reference(retries=3)
	ICustomerInfoService iCustomerInfoService;
	@Autowired
	private BaseUtils baseUtils;
	@Autowired
	private AuditCommentService auditCommentService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private O2oSdService o2oSdService;
	@Autowired
	private OaLoanapplyService oaLoanapplyService;
	@Inject
	private O2oPaymentsService o2oPaymentsService;
	@Value("${o2o.admin.iframe.domain}")
	private String domain;
	@Value("${sd.url}")
	private String sdUrl;
	@Value("${oa.search.url}")
	private String oaUrl;
	@Autowired
	private CreditReportService creditReportService;
	@Autowired
	private O2oOverdueService overdueService;
	@Autowired
	private LoanDetailService loanDetailService;
	@Autowired
	private OaLoanapplyDetailService oaDetailService;
	@Value("${oa.zx.url}")
	private String oaZxUrl;
	@Value("${oa.ns.url}")
	private String oaNsUrl;
	@Value("${oa.yh.url}")
	private String oaYhUrl;
	@Value("${oa.fk.url}")
	private String oaFkUrl;
	@Value("${oa.bzj.url}")
	private String oaBzjUrl;
	@Autowired
	private O2oBrandService o2oBrandService;
	@Autowired
	private O2oOverdueService o2oOverdueService;
	@Autowired
	LoanCheckServicce loanCheckServicce;
	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;
	@Autowired
	AdvanceSettleService advanceSettleService;
	@Autowired
	CustomerShopInfoService shopInfoService;
	@Autowired
	CustomerAssetInfoService assetInfoService;
	@Autowired
	PubDditemService pubDditemService;
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	@Autowired
	private O2oEnterpriseZxService o2oEnterpriseZxService;
	@Override
	public void preHandle() {
		super.preHandle();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "loanManage1");
	}

	/**
	 * 贷前和贷后详情
	 * 
	 * @param showDetailForm
	 * @return
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public String showDetail(ShowDetailForm showDetailForm) {
		O2oLoanapplyEntity loanapply = null;
		
		if (!StringUtil.isEmpty(showDetailForm.getBillCode())) {
			loanapply = o2oloanapplyService.fingByBillCodeDetail(showDetailForm.getBillCode());
			if (loanapply == null) {
				//没有权限返回错误页面
				return "notauthView";
			}
			showDetailForm.setLoanapplyNo(loanapply.getLoanapplyNo());
		}
		loanapply = o2oloanapplyService.findByIdDetail(showDetailForm.getLoanapplyNo());
//		loanapply.setSettleDate(com.eascs.admin.common.utils.StringUtils.parseDate(loanapply.getSettleDate()));
		if (loanapply != null) {//控制数据权限，空则没有权限，不空则有权限
			CreditReport creditReport = creditReportService.queryLoanapplyNo(showDetailForm.getLoanapplyNo(), String.valueOf(StatusContexts.O2O_ZERO));
			O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), showDetailForm.getLoanapplyNo());
			// 查询是否已交保证金、管理费、风险保证金
			ViewContext.put("loanStatus", loanapplyExpandService.queryLoanapplyNo(showDetailForm.getLoanapplyNo()));
			// 审批详情
			String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapply.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			O2oLoanUserEntity loanSorpouseUser = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());
			BrandAndPartnerVo brand = o2oBrandService.queryCodeAndName(loanapply.getLoanapplyNo());
			ViewContext.put("bankData", bankData);
			ViewContext.put("loanUser", loanUser);
			ViewContext.put("loanSorpouseUser", loanSorpouseUser);
			ViewContext.put("agreeUrl", agreeUrl);
			ViewContext.put("domain", domain);
			ViewContext.put("materEntity", materEntity);
			ViewContext.put("brand", brand);
			String isNotContinue = null;
			O2oLoanapplyEntity loanapplyEntity = loanDetailService.queryLoanapplyBillCode(loanapply.getLoanapplyNo(), loanapply.getLoanId(), loanapply.getBillCode(), loanapply.getCreateDate());
			if (loanapplyEntity != null) {
				loanapply.setContinueLoanParenNo(loanapplyEntity.getBillCode());
				isNotContinue = "Y";
			}
			// 面签申报通过才能发起贷后检查
			String loanFlg = loanapply.getLoanFlg();

			if (loanFlg != null && "Y".equals(loanFlg) && !"HN".equals(loanapply.getWfType())) {
				Boolean flag = loanCheckServicce.isStartFlow(loanapply.getBillCode());
				if (!flag) {
					ViewContext.put("ableCheck", "true");
				}
			}
			ViewContext.put("isNotContinue", isNotContinue);
			ViewContext.put("loanapply", loanapply);
			ViewContext.put("creditReport", creditReport);
			User user = UserHolder.getUser();
			ViewContext.put("userNo", user.getNo());
			
			// =================借款人/配偶征信报告 begin=================
			String userZxId="";
			String mateZxId="";
			if (loanUser != null) {
				userZxId = loanUser.getZxNo();
			}
			if (materEntity != null) {
				mateZxId = materEntity.getZxNo();
			}
			
			ViewContext.put("userZxId", userZxId);
			ViewContext.put("mateZxId", mateZxId);
			// =================借款人/配偶征信报告 end=================
			O2oEnterpriseZxEntity O2oEnterpriseZxEntity= o2oEnterpriseZxService.getEntityByloanapply(loanapply.getLoanapplyNo());
			ViewContext.put("O2oEnterpriseZxEntity", O2oEnterpriseZxEntity);
			// 贷前还是贷后判断（是否已放款）
			//判断是否有
			O2OSpecialInterview specialInterview =  o2OSpecialInterviewService.fingCLOFlow(loanapply.getLoanapplyNo()); // 特殊面签申报实体类
			ViewContext.put("specialInterview", specialInterview);
			if (loanapply.getLoanFlg().equals(StatusContexts.O2O_YES)) {
				AdvancedPayment advancedPayment=advanceSettleService.queryEntity(loanapply.getLoanapplyNo(), "CLO");
				ViewContext.put("advancedPayment", advancedPayment);
				return "detail/afterDetail";
			} else {
				return "detail/beforeDetail";
			}
			
		} else {//没有权限返回错误页面
			return "notauthView";
		}
	}

	/**
	 * 借款人信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryLoanUser", method = RequestMethod.GET)
	public String queryLoanUser(DetailFrom detailForm, String type, String approvalStatus) {
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(detailForm.getLoanapplyNo());
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(detailForm.getLoanapplyNo(), detailForm.getLoanId());
		O2oLoanUserEntity loanUser_sensitive = o2oloanapplyService.findLoanUserEntity_sensitive(detailForm.getLoanapplyNo(), detailForm.getLoanId());//脱敏
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(loanUser.getId());
		CustomerBasicInfo customerBasicInfo_sensitive = o2oloanapplyService.getCustomerEntityById_sensitive(loanUser.getId());//脱敏
		int loanCount = o2oLoanUserService.getLoanerCount(detailForm.getLoanId());
		String firstLoanTime = o2oLoanUserService.getStartLoanTime(detailForm.getLoanId());
//		String hhh=getSex(loanUser.getDocumentNo());
		if ( "M".equals(getSex(loanUser.getDocumentNo())) ) {
			ViewContext.put("show_sex", "男");
		} else if ( "F".equals(getSex(loanUser.getDocumentNo())) ) {
			ViewContext.put("show_sex", "女");
		}
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanUser_sensitive", loanUser_sensitive);
		ViewContext.put("type", type);
		ViewContext.put("approvalStatus", approvalStatus);
		ViewContext.put("basic", customerBasicInfo);
		ViewContext.put("basic_sensitive", customerBasicInfo_sensitive);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("numberOfLoans", loanCount);
		ViewContext.put("firstLoanTime", firstLoanTime);
		return "detail/loanUser";
	}
	
	/**
	 * 借款人信息_财务查询详情
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryFinanceLoanUser", method = RequestMethod.GET)
	public String queryFinanceLoanUser(DetailFrom detailForm, String type, String approvalStatus) {
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(detailForm.getLoanapplyNo());
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(detailForm.getLoanapplyNo(), detailForm.getLoanId());
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(loanUser.getId());
		String lastPaymentTime = o2oloanapplyService.getLastPaymentTime(detailForm.getLoanapplyNo(), detailForm.getLoanId());// 查询上一次放款时间
		if(!StringUtil.isEmpty(lastPaymentTime)){
			ViewContext.put("lastPaymentTime", lastPaymentTime);
		}else {
			ViewContext.put("lastPaymentTime", "无");
		}
		int loanCount = o2oLoanUserService.getLoanerCount(detailForm.getLoanId());
		String firstLoanTime = o2oLoanUserService.getStartLoanTime(detailForm.getLoanId());
		if ( "M".equals(getSex(loanUser.getDocumentNo())) ) {
			ViewContext.put("show_sex", "男");
		} else if ( "F".equals(getSex(loanUser.getDocumentNo())) ) {
			ViewContext.put("show_sex", "女");
		}
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("type", type);
		ViewContext.put("approvalStatus", approvalStatus);
		ViewContext.put("basic", customerBasicInfo);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("numberOfLoans", loanCount);
		ViewContext.put("firstLoanTime", firstLoanTime);
		
		return "detail/loanUser_finance";
	}
	/**
	 * 新系统借款人与配偶贷款记录信息
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/otherLoanapply", method = RequestMethod.GET)
	public String queryOtherLoanapply(DetailFrom detailForm) {
		PageResult<Object[]> auditResult = o2oloanapplyService.findOtherLoanapply(detailForm.getLoanapplyNo(),detailForm.getLoanId());
		String title[] = { "贷款单号", "贷款类型", "放款金额", "代偿金额", "放款时间"};
		Button[] titleButtons = new Button[] {ButtonHelper.createOpenButton(null, "/detail?billCode=") };
		PaginationInfo auditInfo = new PaginationInfo(auditResult, title,"/detail?billCode=");
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("OTO_LOAN_TYPE"), null, null };
		auditInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null});
		auditInfo.setSelectDataOptions(selectDataOptions);
		auditInfo.setBuildPagingNavigation(false);
		auditInfo.setFirstRenderColumnIndex(0);
		auditInfo.setBuildRowNumber(true);
		auditInfo.setTitleButtons(titleButtons);
		ViewContext.put("auditResult", auditInfo);
		return "detail/otherLoanpplyResult";
	}
	
	/**
	 * 银行反馈信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/bankMessage", method = RequestMethod.GET)
	public String queryBankMessage(DetailFrom detailForm) {
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(detailForm.getLoanapplyNo());
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(detailForm.getLoanapplyNo(), detailForm.getLoanId());
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(loanUser.getId());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("basic", customerBasicInfo);
		ViewContext.put("loanapply", loanapply);
		
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(detailForm.getLoanId(), detailForm.getLoanapplyNo());
		if(materEntity!=null){
			CustomerBasicInfo materCustomerBasicInfo = o2oloanapplyService.getCustomerEntityById(loanUser.getId());
			ViewContext.put("materBasic", materCustomerBasicInfo);
			ViewContext.put("loanMaterUser", materEntity);
			ViewContext.put("detailForm", detailForm);
		}
		
		return "detail/bankMessage";
	}
	
	/**
	 * 旧系统借款人与配偶贷款记录信息
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/oldotherLoanapply", method = RequestMethod.GET)
	public String queryOldOtherLoanapply(DetailFrom detailForm) {
		PageResult<Object[]> auditResult = o2oloanapplyService.findOtherLoanapply(detailForm.getLoanapplyNo(),detailForm.getLoanId());
		String title[] = { "贷款单号", "贷款类型", "放款金额", "代偿金额", "放款时间"};
		Button[] titleButtons = new Button[] {ButtonHelper.createOpenButton(null, "/detail?billCode=") };
		PaginationInfo auditInfo = new PaginationInfo(auditResult, title,"/detail?billCode=");
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("OTO_LOAN_TYPE"), null, null };
		auditInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null});
		auditInfo.setSelectDataOptions(selectDataOptions);
		auditInfo.setBuildPagingNavigation(false);
		auditInfo.setFirstRenderColumnIndex(0);
		auditInfo.setBuildRowNumber(true);
		auditInfo.setTitleButtons(titleButtons);
		ViewContext.put("auditResult", auditInfo);
		return "detail/otherLoanpplyResult";
	}
	/**
	 * 配偶信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/querySpouseUser", method = RequestMethod.GET)
	public String querySpouseUser(DetailFrom detailForm, String type, String approvalStatus) {
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(detailForm.getLoanId(), detailForm.getLoanapplyNo());
		O2oLoanUserEntity materEntity_sensitive = o2oLoanUserService.findSpouseId_sensitive(detailForm.getLoanId(), detailForm.getLoanapplyNo());//脱敏
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(materEntity.getId());
		CustomerBasicInfo customerBasicInfo_sensitive = o2oloanapplyService.getCustomerEntityById_sensitive(materEntity.getId());//脱敏
		if ( "M".equals(getSex(materEntity.getDocumentNo())) ) {
			ViewContext.put("show_sex", "男");
		} else if ( "F".equals(getSex(materEntity.getDocumentNo())) ) {
			ViewContext.put("show_sex", "女");
		}
		ViewContext.put("materBasic", customerBasicInfo);
		ViewContext.put("materBasic_sensitive", customerBasicInfo_sensitive);
		ViewContext.put("loanMaterUser", materEntity);
		ViewContext.put("loanMaterUser_sensitive", materEntity_sensitive);
		ViewContext.put("loanapply", detailForm);
		ViewContext.put("type", type);
		ViewContext.put("approvalStatus", approvalStatus);
		return "detail/spouseUser";
	}
	
	/**
	 * 配偶信息_财务查询详情
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryFinanceSpouseUser", method = RequestMethod.GET)
	public String queryFinanceSpouseUser(DetailFrom detailForm, String type, String approvalStatus) {
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(detailForm.getLoanId(), detailForm.getLoanapplyNo());
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(materEntity.getId());
		if ( "M".equals(getSex(materEntity.getDocumentNo())) ) {
			ViewContext.put("show_sex", "男");
		} else if ( "F".equals(getSex(materEntity.getDocumentNo())) ) {
			ViewContext.put("show_sex", "女");
		}
		String lastPaymentTime = o2oloanapplyService.getLastPaymentTime(detailForm.getLoanapplyNo(), detailForm.getLoanId());// 查询上一次放款时间
		if(!StringUtil.isEmpty(lastPaymentTime)){
			ViewContext.put("lastPaymentTime", lastPaymentTime);
		}else {
			ViewContext.put("lastPaymentTime", "无");
		}
		ViewContext.put("materBasic", customerBasicInfo);
		ViewContext.put("loanMaterUser", materEntity);
		ViewContext.put("loanapply", detailForm);
		ViewContext.put("type", type);
		ViewContext.put("approvalStatus", approvalStatus);
		return "detail/spouseUser_finance";
	}

	/**
	 * 客户门店信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryShop", method = RequestMethod.GET)
	public String queryShop(DetailFrom detailForm) {
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(detailForm.getLoanId());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(detailForm.getLoanapplyNo());
		ViewContext.put("loanapply",loanapply);
		ViewContext.put("shop", customer.getShopInfoList());
		return "detail/custmerShop";
	}

	/**
	 * 客户门店信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryAssert", method = RequestMethod.GET)
	public String queryAssert(DetailFrom detailForm) {
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(detailForm.getLoanId());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		ViewContext.put("assert", customer.getAssetInfo());
		return "detail/custmerAssert";
	}

	/**
	 * 财务SD审核记录
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryFinancialSd", method = RequestMethod.GET)
	public String queryFinancialSd(DetailFrom detailForm) {
		O2oSDEntity sdEntity = o2oSdService.getById(detailForm.getLoanapplyNo());
		ViewContext.put("o2oSd", sdEntity);
		return "detail/financialSd";
	}
	/**
	 * 财务审核记录
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryFinancialAudit", method = RequestMethod.GET)
	public String financialAudit(ZXPTCWForm zXPTCWForm){
		O2oLoanapplyEntity loanEntity = o2oloanapplyService.findById(zXPTCWForm.getReferId());
		if (null != loanEntity) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			zXPTCWForm = new ZXPTCWForm();
			zXPTCWForm.setLoanapplyno(loanEntity.getLoanapplyNo());
			zXPTCWForm.setReferId(loanEntity.getLoanapplyNo());
			if (null != loanEntity.getEaCooperationDate())
				zXPTCWForm.setEaTime(format.format(loanEntity.getEaCooperationDate()));
			zXPTCWForm.setEaStockNum(loanEntity.getEaStockNum());
			zXPTCWForm.setTakeAvgAmount(loanEntity.getEaPurchaseamount());
			zXPTCWForm.setArrearsAmountTotal(loanEntity.getEaStockBorrowing());
			zXPTCWForm.setCustomerSalesamount(loanEntity.getCustomerSalesamount());
		}
		ViewContext.put("loanEntity", loanEntity);
		ViewContext.put("zXPTCWForm", zXPTCWForm);
		return "workflowcheck/zx_ptcw_view";
	}

	
	/**
	 * 电核反馈
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/phone_message_view", method = RequestMethod.GET)
	public String phoneMessageView(ZXPTCWForm zXPTCWForm){
		O2oLoanapplyEntity loanEntity = o2oloanapplyService.findById(zXPTCWForm.getReferId());
		ViewContext.put("loanEntity", loanEntity);
		return "workflowcheck/phone_message_view";
	}
	
	/**
	 * 贷款审批记录
	 * 
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryAudit", method = RequestMethod.GET)
	public String queryAudit(DetailFrom detailForm) {
		PageResult<Object[]> auditResult = auditCommentService.findAuditList(detailForm.getLoanapplyNo());
		String title[] = { "EA批复额度", "综合费率", "送审银行", "贷款用途", "审批期限", "审批还款方式", "风险补偿金利率", "审批保证金费率", "审批管理费费率", "审批贷款利率", "审批人", "审批时间", "备注" };
		PaginationInfo auditInfo = new PaginationInfo(auditResult, title);
		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("BANKTYPEO2O"), new SelectDataOption("PAYMENTTYPE"), new SelectDataOption("OTOLOANTERM"), new SelectDataOption("OTOREPAYMENTWAY"), null, new SelectDataOption("O2ORISKDEPOSITFEERATE"),
				new SelectDataOption("O2ODEPOSITFEERATE"), new SelectDataOption("O2OMANAGEFEERATE"), null, null, null, null };
		auditInfo.setSelectDataOptions(selectDataOptions);
		auditInfo.setBuildPagingNavigation(false);
		auditInfo.setFirstRenderColumnIndex(0);
		auditInfo.setBuildRowNumber(true);
		auditInfo.setFormats(new Format[] { new DecimalFormat(",##0.00"), null, null, null, null, null, null, null, null, null, null, null });
		ViewContext.put("auditResult", auditInfo);
		return "detail/auditResult";
	}
	/**
	 * 银行放款数据
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/queryFk", method = RequestMethod.GET)
	public String queryFk(DetailFrom detailForm){
		O2oBankLoanData o2oBankLoanData = o2oLoanService.queryBillCode(detailForm.getBillCode());
		ViewContext.put("o2oBankInfo", o2oBankLoanData);
		return "/detail/fkDetail";
	}
	/**
	 * 还款计划
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/repaymentPlan", method = RequestMethod.GET)
	public String queryRepaymentPlan(DetailFrom detailForm){
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setPageSize(Integer.MAX_VALUE);
		o2oPaymentsForm.setBillCode(detailForm.getBillCode());
		PageResult<Object[]> paymentsResult = o2oPaymentsService.paymentsList(o2oPaymentsForm);
		String[] paymentstitles = { "贷款单号", "姓名", "证件号码", "还款期数", "计划还款日期", "剩余本金", "计划还款本金", "计划还款利息" };
		PaginationInfo paymentspaginationInfo = new PaginationInfo(paymentsResult, paymentstitles, "/payments/payments_list/?showPage=");
		paymentspaginationInfo.setBuildPagingNavigation(false);
		paymentspaginationInfo.setFirstRenderColumnIndex(1);
		paymentspaginationInfo.setBuildRowNumber(true);
		ViewContext.put("paymentspaginationInfo", paymentspaginationInfo);
		return "/detail/repaymentPlan";
	}

	/**
	 * 详情页 权限编辑征信
	 * 
	 * @param zXSSYHForm
	 * @return
	 */
	@RequestMapping(value = "/detail/editCredit",method = RequestMethod.GET)
	public String editCredit(ZXPTCWForm zXSSYHForm) {
		O2oLoanapplyEntity loanEntity = o2oloanapplyService.findById(zXSSYHForm.getReferId());
		O2oLoanUserEntity userEntity = o2oLoanUserService.findSpouseId(loanEntity.getLoanId(), zXSSYHForm.getReferId());
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanEntity.getLoanId(), loanEntity.getLoanapplyNo());
		O2oZxEntity o2oZxEntity=null;
		if (loanUser!=null) {
			o2oZxEntity=o2oZxServiceImpl.getEntityById(loanUser.getZxNo());
		}
		if (o2oZxEntity!=null) {
			zXSSYHForm.setBanktype(o2oZxEntity.getZxBank());
		}
		CreditForm creditForm = new CreditForm();
		CreditReport creditReport = creditReportService.queryLoanapplyNo(zXSSYHForm.getReferId(), String.valueOf(StatusContexts.O2O_ZERO));
		if (creditReport != null) {
			// 查询配偶 征信信息
			CreditReport materCredit = creditReportService.queryLoanapplyNo(zXSSYHForm.getReferId(), String.valueOf(creditReport.getId()));
			if (materCredit != null) {
				CreditTransforCreditFrom.CreditTransToForm(creditForm, creditReport, materCredit);
				creditForm.setIds(materCredit.getId());
				creditForm.setParentIds(materCredit.getParentId());
			} else {
				CreditTransforCreditFrom.CreditTransToForm(creditForm, creditReport, null);
			}
		}
		ViewContext.put("loanEntity", loanEntity);
		ViewContext.put("userEntity", userEntity);
		ViewContext.put("creditForm", creditForm);
		ViewContext.put("zXSSYHForm", zXSSYHForm);
		return "workflowcheck/detailEditCredit";
	}

	/**
	 * 附件列表
	 */
	public void queryDatalist(String loanapplyNo) {
		PageResult<Object[]> pageResult = o2oloanapplyService.findO2oDataListEntityById(loanapplyNo);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		ViewContext.put("datalistInfo", datalistInfo);
	}
	
	/**
	 * 逾期信息
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/detail/overdueReport", method = RequestMethod.GET)
	public String queryOverdueReport(String billCode){
		O2oOverdueReport overdueReport= overdueService.queryBillCode(billCode);
		ViewContext.put("overdueReport", overdueReport);
		return "/detail/overdueDetail";
	}

	/**
	 * 近6个月SD交易信息
	 * 
	 * @param customerCode
	 * @return
	 */
	@RequestMapping(value = "/detail/getSdData", method = RequestMethod.GET)
	public String getSdInfo(String customerCode, String cno) {
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM");
		String beginDate = dateFormater.format(new Date());
		String data = "<requestxml><customerCode>" + customerCode + "</customerCode><cno>" + cno + "</cno><beginDate>" + beginDate + "</beginDate></requestxml>";
		Service service = new Service();
		List<Map<String, Object>> info = null;
		try {
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(sdUrl);
			call.setOperationName("getSDStoreSalesAndReceivedData");
			String s = (String) call.invoke(new String[] { data });
			logger.info("resp:", s);
			info = new ArrayList<>();
			Document doc = DocumentHelper.parseText(s);
			Element root = doc.getRootElement().element("statisticsList");
			if (root == null) {
				return null;
			}
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			int count = 0;
			for (Element e : list) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", ++count);
				map.put(e.element("statisticDate").getName(), e.element("statisticDate").getData());
				map.put(e.element("salesMoney").getName(), e.element("salesMoney").getData());
				map.put(e.element("receivedMoney").getName(), e.element("receivedMoney").getData());
				map.put("date", new Date());
				info.add(map);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 下载合同 展示跳转
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping(value = "/contractDetail", method = RequestMethod.GET)
	public String showDetail(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		List<O2oDataListEntity> dataList = o2oloanapplyService.findCodeList(loanapplyNo, FileTypeConstants.DALIST_TYPE_REFUND);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("datalist", dataList);
		return "detail/contractDetail";
	}

	/**
	 * 根据贷款编号跳转新老系统详情界面
	 * 
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/oldsytem", method = RequestMethod.GET)
	public String showOldSystem(String billCode) {
		LoanapplyExpand loanapplyEx = loanapplyExpandService.fingByBillCode(billCode);
		OaLoanapply oaloanapply = oaLoanapplyService.queryBillCode(billCode);
		if (oaloanapply != null) {
			return "redirect:" + oaUrl + billCode;
		} else{
			return "redirect:http://service.o2ojr.eascs.com/detail?loanapplyNo=" + loanapplyEx.getLoanapply_no();
		}
	}

	/**
	 * 下载o2o金融合作协议 展示跳转
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/protocolDetail", method = RequestMethod.GET)
	public String protocolDetail(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = o2oloanapplyService.findById(loanapplyNo);
		
		O2oLoanUserEntity loanUserEntity = o2oloanapplyService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());//借款人基本信息
		CustomerBasicInfo customerBasicInfo = o2oloanapplyService.getCustomerEntityById(loanUserEntity.getId());//借款人扩展信息
		O2oLoanUserEntity mate = o2oLoanUserService.findSpouseId(loanUserEntity.getLoanId(), loanapplyNo);//配偶
		CustomerAssetInfo assetInfo = assetInfoService.queryById(loanapplyNo);
		CustomerShopInfoEntity shop = new CustomerShopInfoEntity();
		List<CustomerShopInfoEntity> infoList = shopInfoService.list(loanapplyNo);//门店
		if (!infoList.isEmpty()) {
			if (infoList.size() > 1) {
				for (CustomerShopInfoEntity shopInfo : infoList) {
					if (shopInfo.getShoptype().equals("MAN")) {// 客户主门店里面的营业面积
						shop = shopInfo;
					}
				}
			} else {
				shop = infoList.get(0);
			}
		}
		
		
//		QueryCustomerVO vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
//		O2oLoanUserEntity userEntity = o2oLoanUserService.findById(loanapply.getLoanId(), loanapplyNo);

//		vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		vo.setShoptype("MAN");
//		CustomerShopInfoEntity shop = iCustomerInfoService.getCustomerShopInfoEntity(vo);
		
		// 个人基本信息
		ViewContext.put("basic", loanUserEntity);
		// 个人信息扩展
		ViewContext.put("expan", customerBasicInfo);
		// 门店信息
		ViewContext.put("shop", shop);
		// 资产信息
		ViewContext.put("assert", assetInfo);
		// 借款信息
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("loanUser", loanUserEntity);
		// 主门店信息
		ViewContext.put("mainShop", shop);
		// 配偶信息
		ViewContext.put("mate", mate);
		
		if (StringUtil.isNotBlank(customerBasicInfo.getBorrowerCensusRegister())) {
			// 查数据字典--户口所在地，dd_no='22'
			PubDditem p = pubDditemService.queryPubDditemCRM("22", customerBasicInfo.getBorrowerCensusRegister());// 户口所在地
			if (p != null) {
				ViewContext.put("borrowerCensusRegisterPD", p.getItemName());// 户口所在地
			}
		} else {
			ViewContext.put("borrowerCensusRegisterPD", "");// 户口所在地
		}
		
		if (customerBasicInfo != null) {
			String recipientAdress="";//有效联系地址	借款人的收件地址
         	if (StringUtil.isNotBlank(customerBasicInfo.getRecipientProvince())) {
         		// 查数据字典--所在省，dd_no='9'
         		PubDditem p = pubDditemService.queryPubDditemCRM("9",customerBasicInfo.getRecipientProvince());// 所在省
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}
        
			if (StringUtil.isNotBlank(customerBasicInfo.getRecipientCity())) {
				// 查数据字典--所在市，dd_no='10'
				PubDditem p = pubDditemService.queryPubDditemCRM("10",customerBasicInfo.getRecipientCity());// 所在市
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}
			
			if (StringUtil.isNotBlank(customerBasicInfo.getRecipientCounty())) {
				PubDditem p = pubDditemService.queryPubDditemCRM("11",customerBasicInfo.getRecipientCounty());// 所在县
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}

			if (customerBasicInfo.getRecipientAddress() != null) {
				recipientAdress = recipientAdress + customerBasicInfo.getRecipientAddress();
			}
			ViewContext.put("recipientAdress", recipientAdress);// 收件地址
		}else {
			ViewContext.put("recipientAdress", "");// 收件地址
		}
		
		return "detail/protocolDetail";
	}
	/**
	 * 老系统基本资料
	 * 
	 * @param billCode
	 * @return
	 */
	public String queryOaBasic(String billCode) {
		logger.info("查询老系统基本资料CODE：[{}]", billCode);
		OaLoanDetailEntity oaLoanDetail = oaDetailService.queryBasic(billCode);
		ViewContext.put("oaLoanDetail", oaLoanDetail);
		ViewContext.put("oaZxUrl", oaZxUrl + oaLoanDetail.getBillcodecredit());
		ViewContext.put("oaNsUrl", oaNsUrl + oaLoanDetail.getBillCode());
		ViewContext.put("oaYhUrl", oaYhUrl + oaLoanDetail.getBillCode());
		ViewContext.put("oaFkUrl", oaFkUrl + oaLoanDetail.getBillCode());
		ViewContext.put("oaBzjUrl", oaBzjUrl + oaLoanDetail.getBillCode());
		ViewContext.put("oaXdUrl", "/rcloan/reloan?ty=OLD&billCode="+ oaLoanDetail.getBillCode());
		return "detail/oaDetail";
	}

	/**
	 * 老系统逾期详情
	 * 
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/oaDetail/overdue", method = RequestMethod.GET)
	public String queryOaOverdue(String billCode,String flag) {
		PageResult<Object[]> oaOverdueList = o2oOverdueService.queryOverDue(billCode);
		String title[] = { "贷款单号", "借款人", "代偿总额（元）","代偿回款总额（元）", "代偿余额（元）","逾期总额" };
		Button detail = ButtonHelper.createOpenButton(null, "/detail?billCode=");
		Button dc = ButtonHelper.createOpenButton(null, "/badloan/index?billcodeea=");
		Button dch = ButtonHelper.createOpenButton(null, "/badloan/alllist?billCode=");
		Button yq = ButtonHelper.createOpenButton(null, "/overdue/index?billCode=");
		Button[] titleButtons = new Button[] { };
		if (!StringUtils.isEmpty(flag)) {
			titleButtons = new Button[] { detail, null, dc, dch, null, yq };
		} else {
			titleButtons = new Button[] { null, null, dc, dch, null, yq };
		}
		PaginationInfo auditInfo = new PaginationInfo(oaOverdueList, title, null);
		auditInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		auditInfo.setBuildPagingNavigation(false);
		auditInfo.setFirstRenderColumnIndex(0);
		auditInfo.setBuildRowNumber(true);
		auditInfo.setTitleButtons(titleButtons);
		ViewContext.put("oaOverdueInfo", auditInfo);
		return "/detail/OaoverdueDetail";
	}

	/**
	 * 老系统垫付（代偿）详情
	 * 
	 * @param billCode
	 * @return
	 */
	@RequestMapping(value = "/oaDetail/df", method = RequestMethod.GET)
	public String queryOaDf(String billCode) {
		OaPay oaPay = oaDetailService.queryOaPay(billCode);
		ViewContext.put("oaPay", oaPay);
		return "/detail/oaPay";
	}
	
	/**
	 * 电核反馈
	 * @param detailForm
	 * @return
	 */
	@RequestMapping(value = "/detail/tsmqsb_detail", method = RequestMethod.GET)
	public String tsmqsbDetail(ZXPTCWForm zXPTCWForm){
		O2OSpecialInterview specialInterview =  o2OSpecialInterviewService.queryEntity(zXPTCWForm.getReferId()); // 特殊面签申报实体类
		ViewContext.put("specialInterview", specialInterview);
		return "workflowcheck/tsmqsb_detail";
	}
	
	@RequestMapping(value = "/sdView")
	public String sdView() {
		
		return "daliansd/view";
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               获取夫妻双方贷款记录
	 *               </p>
	 * @author CXW
	 * @date 2017年7月31日 下午4:38:15
	 * @param loanNo:用户客户表Id，spouseLoanNo:用户配偶id
	 * @version V1.0
	 */
	public String getUserAndWifeLoanRecord(String loanNo, String spouseLoanNo){
	
		return "";
	}
	
	
	// 根据身份证信息获取年龄
	public String getSex(String UUserCard) {
		// 获取出生日期
		// UUserCard.substring(6, 10) + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
		// 获取性别
		if (Integer.parseInt(UUserCard.substring(16, 17)) % 2 == 1) {
			// alert("男");
			return "M";
		} else {
			// alert("女");
			return "F";
		}
	}
	
	
}
